package com.bawei.module_vehicle.ui.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bawei.module_vehicle.databinding.ItemCarInfoBinding
import com.bawei.module_vehicle.model.CarModel

class CarAdapter(
    private val onEditClick: (CarModel) -> Unit,
    private val onDeleteClick: (CarModel) -> Unit
) : ListAdapter<CarModel, CarAdapter.CarViewHolder>(CarDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CarViewHolder {
        val binding = ItemCarInfoBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return CarViewHolder(binding)
    }

    override fun onBindViewHolder(holder: CarViewHolder, position: Int) {
        val car = getItem(position)
        holder.bind(car)

        // 编辑按钮点击
        holder.binding.btnEdit.setOnClickListener {
            onEditClick(car)
        }

        // 删除按钮点击
        holder.binding.btnDelete.setOnClickListener {
            onDeleteClick(car)
        }
    }

    class CarViewHolder(val binding: ItemCarInfoBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(car: CarModel) {
            binding.tvLicensePlate.text = car.licensePlate
            binding.tvOwnerModel.text = car.ownerName
        }
    }
}

class CarDiffCallback : DiffUtil.ItemCallback<CarModel>() {
    override fun areItemsTheSame(oldItem: CarModel, newItem: CarModel): Boolean {
        return oldItem.id == newItem.id
    }

    override fun areContentsTheSame(oldItem: CarModel, newItem: CarModel): Boolean {
        return oldItem == newItem
    }
}